/*
*	拖拽插件
*/

;(function ($) {
	'use strict';

	var Drag = function (element, options, index) {
		var self = this;
		self.element = element;
		self.options = options;
		self.index = index;
		
		//  是否全屏拖动
		if (self.options.fullscreen === true) {
			self.options.top = 0;
			self.options.left = 0;
			self.options.width = $(window).width();
			self.options.height = $(window).height();
		}
		else {
			self.element.css({
				'top': self.options.top, 
				'left': self.options.left,
			});
		}

		//  bind
		self.bind_event();
		return self;
	};

	Drag.prototype = {
		constructor: Drag,
		bind_event: function () {
			var self = this;
			self.element.on('mousedown.drag', drag_start)

			//  拖拽 —— 鼠标按下
			function drag_start(e) {
				var land_x = e.clientX - self.element.offset().left,
					land_y = e.clientY - self.element.offset().top;
				drag_move(land_x, land_y);
				drag_end();
				return false;
			}

			//  拖拽 —— 鼠标移动
			function drag_move(land_x, land_y) {
				$(document).on('mousemove.drag', function (e) {
					e.preventDefault();
					var l = e.clientX - land_x, 
						t = e.clientY - land_y,
						w_sc = $(window).scrollTop();

					//  防止拖出规定区域
					if (l < self.options.left) {
						l = self.options.left;
					}
					else if (l > self.options.width - self.element.width() + self.options.left) {
						l = self.options.width - self.element.width() + self.options.left;
					}
					if (t < self.options.top + w_sc) {
						t = self.options.top + w_sc;
					}
					else if (t > self.options.height - self.element.height() + self.options.top + w_sc) {
						t = self.options.height - self.element.height() + self.options.top + w_sc;
					}
					self.element.css({
						'left': l, 
						'top': t,
					});
				});
			}

			//  拖拽 —— 鼠标抬起
			function drag_end() {
				$(document).on('mouseup.drag', function (e) {
					e.preventDefault();
					$(this).off('.drag');
				});
			}
			return self;
		}
	};

	//  调用执行
	$.fn.drag = function (options) {
		options = $.extend({}, $.fn.drag.defaults, options);
		var element = this,
			index = this.attr('data-drag-index'),
			drag = new Drag(element, options, index);
		return this;
	};

	//  默认参数
	$.fn.drag.defaults = {
		top: 200,
		left: 700,
		width: 500,
		height: 500,
		fullscreen: false,
	};
	
}($));
